package com.mojawa.mj_util.anima

import android.view.Choreographer

class LineDrawingAnimator(private val totalDuration: Long, private val callback: (Float) -> Unit) {
    private var startTime: Long = 0
    private val frameCallback = object : Choreographer.FrameCallback {
        override fun doFrame(frameTimeNanos: Long) {
            val elapsedTime = System.currentTimeMillis() - startTime
            val fraction = elapsedTime.toFloat() / totalDuration
            if (fraction <= 1.0f) {
                // 回调返回当前进度
                callback(fraction)
                // 请求下一帧
                Choreographer.getInstance().postFrameCallback(this)
            } else {
                // 动画结束时设定进度为1.0
                callback(1.0f)
            }
        }
    }

    fun start() {
        startTime = System.currentTimeMillis()
        Choreographer.getInstance().postFrameCallback(frameCallback)
    }
}